<?php

namespace zhtfrontend\models\datas;

use common\components\helpers\Fun;
use Yii;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use common\components\extenders\MenuManage;
use yii\base\Model;
use yii\helpers\Html;

/**
 * This is the model class for table "{{%headmaster}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $img
 * @property integer $mechanic_id
 * @property string $description
 * @property integer $sex
 * @property integer $age
 * @property string $address
 * @property string $mobile
 * @property string $area
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $email
 * @property integer $cate_id
 * @property string $account
 */
class Headmaster extends \zhtfrontend\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%headmaster}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mechanic_id', 'sex', 'age', 'status', 'cate_id'], 'integer'],
            [['mechanic_id', 'sex', 'age', 'cate_id', 'mobile', 'name'], 'required'],
            ['mobile', 'match', 'pattern' => '/^([1][3-8]+\\d{9})$/', 'message' => '手机号码格式错误', 'on' => 'create'],
            [['description'], 'string'],
            [['name', 'area'], 'string', 'max' => 50],
            [['img', 'address'], 'string', 'max' => 200],
            [['mobile'], 'string', 'max' => 11],
            [['email'], 'string', 'max' => 32],
            [['email'], 'email'],
            [['mobile'], 'unique'],
            ['age', 'compare', 'compareValue' => 0, 'operator' => '>='],
            ['age', 'check_age','on'=>['create']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', '自增id'),
            'name' => Yii::t('zhtfrontend', '姓名'),
            'img' => Yii::t('zhtfrontend', '照片'),
            'mechanic_id' => Yii::t('zhtfrontend', '机构id'),
            'description' => Yii::t('zhtfrontend', '描述'),
            'sex' => Yii::t('zhtfrontend', '性别'),
            'age' => Yii::t('zhtfrontend', '年龄'),
            'address' => Yii::t('zhtfrontend', '地址'),
            'mobile' => Yii::t('zhtfrontend', '手机'),
            'area' => Yii::t('zhtfrontend', '地区'),
            'status' => Yii::t('zhtfrontend', '是否启用'),
            'created_at' => Yii::t('zhtfrontend', '添加时间'),
            'updated_at' => Yii::t('zhtfrontend', '修改时间'),
            'email' => Yii::t('zhtfrontend', '邮箱'),
            'cate_id' => Yii::t('zhtfrontend', '分类'),
            'account' => Yii::t('zhtfrontend', '账号'),
        ];
    }

    public function extraFields()
    {
        return [
            'mechanic_name' => function () {
                return ($this->mechanic != null) ? $this->mechanic->name : '';
            },
            'deleteHandle' => function ($data) {
                $teacher = Teacher::find()->where(['parent_id' => $this->id])->all();
                $class_manage = ClassManage::find()->where(['headmaster' => $this->id])->andWhere(['!=', 'status', 2])->all();
                if (($teacher != null && $class_manage != null)) {
                    return '<button class="yx-btn-disabled1" type="button" disabled>删除</button>';
                } else {
                    return Html::a('删除', 'javascript:;', ['rel' => 'record_item_confirm', 'class' => 'btn yx-class-about yx-bga0a0a0 yx-radius2', 'data' => ['message' => '确定要删除' . $data['name'] . '吗？', 'url' => Fun::url(['headmaster/delete', 'id' => $data['id']])]]);
                }
            },
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],

        ]);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $model = new Admin();
            $model->username = $this->mobile.'_h';
            $model->email = $this->email;
            $model->mechanic_id = $this->mechanic_id;
            $model->name = $this->name;
            $model->mobile = strlen($this->mobile) == 11 ? $this->mobile : '';
            $model->role = 'class_teacher';
            $model->teacher_id = $this->id;//若是班主任，存放headmaster_id
            $model->created_at = $this->created_at;
            $model->logo = $this->img;
            $model->password = \Yii::$app->security->generatePasswordHash($this->mobile);
            if ($model->save(false)) {
                $auth = \Yii::$app->authManager;
                $auth->assign($auth->getRole($model->role), $model->id);
            }
        } else {
            $model = Admin::findOne(['role' => 'class_teacher', 'teacher_id' => $this->id]);
            $admin = Admin::findOne(['username' => $this->mobile . '_h']);
            if(empty($admin)){
                $model->username = $this->mobile.'_h';
                $model->password = \Yii::$app->security->generatePasswordHash($this->mobile);
                $model->save(false);
            }
            $teacher = Teacher::find()->where(['parent_id' => $this->id])->all();
            foreach ($teacher as $k => $v) {
                $v->cate_id = $this->cate_id;
                $v->save(false);
            }
        }
    }

    public function check_age($attribute){
        if(strlen($this->$attribute)>4 || strlen($this->$attribute)<4){
            $this->addError($attribute, Yii::t('common', '请输入正确的年份'));
        }

    }

    public function afterDelete()
    {
        parent::afterDelete();
        $adminClass = Admin::find()->where(['teacher_id' => $this->id, 'role' => 'class_teacher'])->one();
        if ($adminClass) {
            $adminClass->delete();
        }
    }

    public function getMechanic()
    {
        return $this->hasOne(Mechanic::className(), ['id' => 'mechanic_id']);
    }


}
